// src/features/channels/components/create-channel-modal.tsx
import React, {useState} from 'react';
import {Dialog, DialogContent, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {useCreateChannelModal} from "@/features/channels/store/use-create-channel-modal";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {useCreateChannel} from "@/features/channels/api/use-create-channel";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useRouter} from "next/navigation";
import {toast} from "sonner";

const CreateChannelModal = () => {
    const router = useRouter()

    const {mutate, isPending} = useCreateChannel()
    const workspaceId = useWorkspaceId();

    const [open, setOpen] = useCreateChannelModal()
    const [name, setName] = useState('');

    const handleClose = () => {
        setName('')
        setOpen(false)
    }
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // 输入的 空格 转 -
        const value = e.target.value.replace(/\s+/g, '-').toLowerCase()
        setName(value)
    }
    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        await mutate(
            {name, workspaceId},
            {
                onSuccess(id) {
                    toast.success("Channel created")
                    router.push(`/social/workspace/${workspaceId}/channel/${id}`)
                    handleClose()
                },
                onError() {
                    toast.error("Failed to create channel")
                },
            }
        )
    }

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Add a channel</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit}
                      className={`space-y-4`}>
                    <Input
                        value={name}
                        disabled={isPending}
                        onChange={handleChange}
                        required
                        autoFocus
                        minLength={3}
                        maxLength={80}
                        placeholder={'e.g. plan-budget'}
                    />
                    <div className={`flex justify-end`}>
                        <Button disabled={false}>
                            Create
                        </Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
};

export default CreateChannelModal;